package com.xia.qianke.controller;

import com.xia.qianke.entity.QkPostData;
import com.xia.qianke.entity.client.ApplyMsg;
import com.xia.qianke.entity.client.CkMsg;
import com.xia.qianke.entity.client.Client;
import com.xia.qianke.serivce.Qk;
import com.xia.qianke.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @ClassName QkController
 * @Description TODO
 * @Author XJY
 * @Date 2022/7/6 16:16
 * @Version 1.0
 **/
@RestController
public class QkController {
    @Autowired
    Qk qk;
    @Autowired
    HttpUtils httpUtils;

    @PostMapping("/klhd/check_user")
    public CkMsg checkUser(@RequestBody Map phoneMd5){
        CkMsg ckMsg = new CkMsg ();
        String md5 = (String) phoneMd5.get ("phoneMd5");
        if(StringUtils.isEmpty (md5)){
            ckMsg.setMsg ("未传输数据");
            ckMsg.setCode ("-1000");
            return ckMsg;
        }
        if (qk.checkUser (md5)){
            ckMsg.setCode ("0000");
            ckMsg.setMsg ("可以借款");
            return ckMsg;
        }
        ckMsg.setMsg ("用户在机构有未完成的借款");
        ckMsg.setCode ("1002");
        return ckMsg;
    }

    @PostMapping("/klhd/apply")
    public ApplyMsg apply(@RequestBody Client client){
        if(client != null && !StringUtils.isEmpty (client.getName ()) && !StringUtils.isEmpty (client.getPhone ())){
            String md5DigestAsHex = DigestUtils.md5DigestAsHex (client.getPhone ().getBytes (StandardCharsets.UTF_8));
            if (qk.checkUser (md5DigestAsHex)) {
                //发送给仟客端
                QkPostData qkPostData = qk.postData (client);
                if (qkPostData.getErrmsg ().equals ("ok")) {
                    //存入本地数据库
                    qk.addMd5 (client);
                    qk.sendVxMsg ();
                    return new ApplyMsg ("0000","接收成功");
                }
                return new ApplyMsg ("1000","接受失败");
            }
            return new ApplyMsg ("1000","该用户已经存在");
        }
        return new ApplyMsg ("1000","必要数据为空");
    }
}
